from collections import namedtuple
import csv
import os
import sqlalchemy.orm.exc

SqliteExportRecord = namedtuple('SqliteExport', 'unit,address,latitude,longitude')

def sqlite_export_records(filename):
    csvfile = open(filename, "rb")
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    reader = csv.reader(csvfile, dialect)    
    for record in map(SqliteExportRecord._make, reader):
        yield record


if __name__ == "__main__":
    from pyramid.paster import bootstrap
    env = bootstrap('../development.ini')
    

    from cpswarehouse.models import DBSession, SchoolDimension
    import transaction

    #import pdb; pdb.set_trace()
    
    session = DBSession()
    data_filename = "sqlite_export.csv"

    #should take this from arguments
    records = sqlite_export_records(data_filename)


    for record in records:
        try:
            school = session.query(SchoolDimension).filter_by(unit=record.unit).one()
            school.address = record.address
            school.latitude = record.latitude
            school.longitude = record.longitude
            transaction.commit()
        except sqlalchemy.orm.exc.NoResultFound:
            print "Could not find school with unit: %s" % record.unit
        #print school

    #transaction.commit()
